import type { TrackData } from './components/TrackTypes'
import { useApplianceStore } from '../../src/store/appliance'
import { reportEventData } from '../dataReport/dataReportUtil'
import { useAuthStore } from '../../src/store/auth'
import i18n from '@/i18n'
import store from '@/store'
import { useGlobalStore } from '@/store/global'
import { getControllerContext } from '@/controller/common/context'
const globalStore = useGlobalStore(store)

export enum TrackType {
  BusinesssScene = 0, // 业务场景，
  ApplianceDetail, //家电详情页非家电操作埋点,
}

/** 说明
 * ApplianceDetail会自动包含家电相关信息，不需要在trackData里面另外增加
 * BusinesssScene 会自动增加isLogin(是否登录的标识),不需要在rackData里面另外增加
 */

/**
 * 埋点
 * @param trackId  埋点ID/埋点key
 * @param trackData 埋点的数据内容:属性和值
 * @param trackType 埋点场景类型
 */
export function trackEvent(trackId: string, trackData: TrackData, trackType: TrackType, buttonId?: string | unknown) {
  if (globalStore.is_virtual) {
    return
  }
  if (trackData === void 0) {
    trackData = {}
  }
  // 对于非数据请求类的埋点 都默认为此属性为YES
  if (!Object.keys(trackData).includes('successOrNot')) {
    trackData.successOrNot = true
  }
  trackData.button_id = buttonId ? buttonId : trackId

  switch (trackType) {
    case TrackType.BusinesssScene: {
      // 业务场景
      let isLogin = useAuthStore().isLogin
      trackData.isLogin = isLogin
      reportEventData(trackId, trackData)
      break
    }
    case TrackType.ApplianceDetail: {
      // 家电详情
      // 获取家电相关信息
      handleApplianceInfo(trackData)
      reportEventData(trackId, trackData)
      break
    }
  }
}

/**
 * 处理家电信息
 * @param trackData
 */
function handleApplianceInfo(trackData: TrackData = {}) {
  // 获取本地存储的家电信息
  let applianceHaId = useApplianceStore().current?.haId || ''
  let applianceVib = useApplianceStore().current?.vib || ''
  let applianceType = useApplianceStore().current?.type || ''
  let applianceBrand = useApplianceStore().current?.brand || ''
  // 记录家电基本信息
  trackData.appliance_haid = applianceHaId
  trackData.appliance_vib = applianceVib
  trackData.appliance_type = applianceType
  trackData.appliance_brand = applianceBrand

  try {
    let operationState: any = null
    if (applianceHaId) {
      operationState = getControllerContext(applianceHaId)?.store.operationState
      if (operationState?.indexOf('.') != -1) {
        let state: any = operationState.split('.').slice(-1).toString()
        operationState = state
      }
      operationState = operationState || 'unknown'
    }
    trackData.operationState = operationState
  } catch (error) {
    console.error('获取家电运行状态报错')
    trackData.operationState = null
  }
}
